class WebSocketService {
    constructor() {
        this.socket = null;
    }

    connect(url) {
        this.socket = uni.connectSocket({
            url,
            success: () => console.log("WebSocket 连接成功"),
            fail: (err) => console.log("WebSocket 连接失败", err)
        });

        this.socket.onMessage((res) => {
            console.log("收到消息：", res.data);
        });

        this.socket.onClose(() => {
            console.log("WebSocket 连接关闭，尝试重连...");
            setTimeout(() => this.connect(url), 3000);
        });

        this.socket.onError((err) => {
            console.error("WebSocket 错误:", err);
        });
    }

    sendMessage(message) {
        if (this.socket) {
            this.socket.send({
                data: JSON.stringify(message),
                success: () => console.log("消息发送成功"),
                fail: (err) => console.log("消息发送失败", err)
            });
        }
    }
}

// 只创建一个 WebSocket 实例
const webSocketService = new WebSocketService();
export default webSocketService;
